<?php

namespace app\job;

use app\cps\service\DebugLosService;
use think\queue\Job;
use think\facade\Db;
use app\common\Common;
use think\facade\Cache;
use think\facade\Log;
use app\model\DebugLogs;

// 转化回传队列
class PostBack
{
    public function fire(Job $job, $info)
    // public function fire($info)
    {
        // 获取redis对象
        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $link_id = $info['link_id'];
        $orderId = $info['id'];

        try {
            // 获取该用户的充值次数数据
            $payData = Db::name('pay_record')->where(['uid' => $info['uid'], 'status' => 1, 'link_id' => $info['link_id'], 'advertiser_id' => $info['advertiser_id']])->field('id')->select()->toArray();
            if (count($payData) == 1) {
                Db::name('pay_record')->where(['id' => $orderId])->update([
                    'is_first_recharge' => 1
                ]);
            }

            // 获取该链接的回传相关设置
            $linkData = Db::name('link')->where(['id' => $info['link_id']])->field('is_open, media_id, echo_rate, echo_rule_config_id, official_account_id, is_open_low_recharge_not_echo, not_echo_recharge_price, edit_echo_rate_time, token, is_capitalization, video_id, designated_amount_echo, design_switch, is_new_back_setting')->find();

            if ($linkData['is_open'] != 1) {
                // 该链接未开启回传
                $job->delete();
                return;
            }

            // 是否是新版自定义回传配置
            $backData = [];
            if ($linkData['is_new_back_setting'] == 2) {
                $backData = Db::name('echo_rule_config')->where(['id' => $linkData['echo_rule_config_id']])->field('type, back_rate_type, echo_rate, pass, leak, design_switch, designated_amount_echo, is_open_low_recharge_not_echo, not_echo_recharge_price, edit_echo_time')->find();

                // 如果开启了低充值不回传并且充值低于设置的最低回传充值将不回传
                if ($backData['is_open_low_recharge_not_echo'] == 1 && round($info['total_fee'], 2) < round($backData['not_echo_recharge_price'], 2)) {
                    $job->delete();
                    return;
                }

            } else {
                // 如果开启了低充值不回传并且充值低于设置的最低回传充值将不回传
                if ($linkData['is_open_low_recharge_not_echo'] == 1 && round($info['total_fee'], 2) < round($linkData['not_echo_recharge_price'], 2)) {
                    $job->delete();
                    return;
                }
            }

            // 如果用户在该链接充值第一笔未回传 则不回传
            $transferBackRecordData = Db::name('transfer_back_record')->where(['uid' => $info['uid'], 'status' => 1, 'link_id' => $info['link_id'], 'advertiser_id' => $info['advertiser_id']])->field('id')->find();

            if (count($payData) > 1 && empty($transferBackRecordData)) {
                $job->delete();
                return;
            }

            if ($linkData['is_new_back_setting'] == 2) {
                // 获取该用户在该链接的回传数据
                if (!empty($transferBackRecordData) && $backData['type'] != 2 && time() < strtotime($info['activation_time']) + 7 * 86400) {
                    // 如果该用户再该链接回传过并且当前时间小于激活时间加7天的时间的话直接回传
                    $boolId = $this->backPlatform($linkData, $info, 0);
                    $job->delete();
                    return;
                }
            } else {
                // 获取该用户在该链接的回传数据
                if (!empty($transferBackRecordData) && $linkData['echo_rule_config_id'] != 2 && time() < strtotime($info['activation_time']) + 7 * 86400) {
                    // 如果该用户再该链接回传过并且当前时间小于激活时间加7天的时间的话直接回传
                    $boolId = $this->backPlatform($linkData, $info, 0);
                    $job->delete();
                    return;
                }
            }

            // 0按T+7全量回传 1按自然日回传 2只回传首单
            if (!empty($backData) && $backData['type'] == 2 && !empty($transferBackRecordData)) {
                // 如果回传过首单 则后续不回传
                $job->delete();
                return;
            } else if ($linkData['is_new_back_setting'] == 1 && $linkData['echo_rule_config_id'] == 2 && !empty($transferBackRecordData)) {
                // 如果回传过首单 则后续不回传
                $job->delete();
                return;
            } else if ($linkData['is_new_back_setting'] == 1 && $linkData['echo_rule_config_id'] == 1) {
                // 每天0点前激活的用户充值0点后不会传
                $activationTime = date('Y-m-d') . ' 00:00:00';

                if (strtotime($info['activation_time']) < strtotime($activationTime)) {
                    $job->delete();
                    return;
                }
            } else if ($linkData['is_new_back_setting'] == 2 && $backData['type'] == 1) {
                // 每天0点前激活的用户充值0点后不会传
                $activationTime = date('Y-m-d') . ' 00:00:00';

                if (strtotime($info['activation_time']) < strtotime($activationTime)) {
                    $job->delete();
                    return;
                }
            } else {
                // 如果当前时间大于激活时间+7天不回传
                if (time() > strtotime($info['activation_time']) + 7 * 86400) {
                    $job->delete();
                    return;
                }
            }

            $type = 0;
            if (($linkData['is_new_back_setting'] == 1 && !empty($linkData['design_switch'])) || ($linkData['is_new_back_setting'] == 2 && !empty($backData['design_switch']))) {
                // 有设置指定金额回传
                if ($linkData['is_new_back_setting'] == 1) {
                    $designatedAmountEcho = json_decode($linkData['designated_amount_echo'], true);
                } else {
                    $designatedAmountEcho = json_decode($backData['designated_amount_echo'], true);
                }

                $designatedAmount = array_column($designatedAmountEcho, 'price');

                if (!in_array($info['total_fee'], $designatedAmount)) {

                    Log::info(json_encode($info).' -------- 支付金额： '. $info['total_fee'] .' 未在指定回传金额设置里面 -------- ');
                    // 按常规回传率设置回传
                    $echoNumData = $this->conventionalEcho($linkData, $redis, $info, $backData);
                    $type = $echoNumData['type'];
                    $thisLinkOrderNum = $echoNumData['this_link_order_num'];
                    $backSuccessNum = $echoNumData['back_success_num'];
                } else {

                    $key = array_search($info['total_fee'], $designatedAmount);

                    $echoInfo = $designatedAmountEcho[$key];

                    $price = intval($info['total_fee'] * 100);
                    $updateTime = $echoInfo['update_time'];

                    $startTime = strtotime(date('Y-m-d' . ' 00:00:00'));
                    $endTime = strtotime(date('Y-m-d' . ' 23:59:59'));

                    $echoRate = $echoInfo['rate'];

                    if ($updateTime > $startTime && $updateTime < $endTime) { // 判断是否再今日时间之内

                        // 按该链接修改回传率的时间之后的支付数和回传数开始计算比例
                        $thisLinkOrderNum = $redis->get('design-amount-pay-success-order-num-' . $price . '-' . $updateTime . '-' . $info['advertiser_id']); // 指定金额在该投放计划的订单充值人数
                        $backSuccessNum = $redis->get('design-amount-echo-success-order-num-' . $price . '-' . $updateTime . '-' . $info['advertiser_id']); // 指定金额在该投放计划的回传人数

                        if (empty($thisLinkOrderNum) || empty($backSuccessNum)) {
                            if (!empty($linkData['echo_rule_config_id'])) {
                                $where = [
                                    ['advertiser_id', '=', $info['advertiser_id']],
                                    ['status', '=', 1],
                                    ['pay_time', '>=', $updateTime],
                                    ['activation_date', '=', date('Ymd')],
                                    ['link_id', '=', $info['link_id']],
                                    ['total_fee', '=', $info['total_fee']]
                                ];
                            } else {
                                $where = [
                                    ['advertiser_id', '=', $info['advertiser_id']],
                                    ['status', '=', 1],
                                    ['pay_time', '>=', $updateTime],
                                    ['link_id', '=', $info['link_id']],
                                    ['total_fee', '=', $info['total_fee']]
                                ];
                            }

                            // 这个链接修改回传率的时间之后的支付订单数（每个用户仅统计一次）
                            $thisLinkOrderNum = Db::name('pay_record')->where($where)->group('uid')->count();

                            // 这个链接修改回传率的时间之后的回传成功数（每个用户仅统计一次）
                            $where = [
                                ['advertiser_id', '=', $info['advertiser_id']],
                                ['status', '=', 1],
                                ['created_at', '>', $updateTime],
                                ['link_id', '=', $info['link_id']],
                                ['echo_rule_config_id', '<>', '-1'],
                                ['echo_amount', '=', $price]
                            ];
                            $backSuccessNum = Db::name('transfer_back_record')->where($where)->group('uid')->count();

                            $redis->set('design-amount-echo-success-order-num-' . $price . '-' . $updateTime . '-' . $info['advertiser_id'], $backSuccessNum, 3000);
                            $redis->set('design-amount-pay-success-order-num-' . $price . '-' . $updateTime . '-' . $info['advertiser_id'], $thisLinkOrderNum, 3000); // redis存50分钟
                        } else {
                            // 有缓存回传数据
                            $redis->incr('design-amount-pay-success-order-num-' . $price . '-' . $updateTime . '-' . $info['advertiser_id']); // redis自增1
                            $thisLinkOrderNum = $thisLinkOrderNum + 1;
                        }

                        $type = 3;
                    } else {

                        // 修改回传率时间不在今日
                        $thisLinkOrderNum = $redis->get('design-amount-pay-success-order-num-' . $price . '-' . date('Ymd') . '-' . $info['advertiser_id']); // 指定金额在该投放计划的今日订单充值人数
                        $backSuccessNum = $redis->get('design-amount-echo-success-order-num-' . $price . '-' . date('Ymd') . '-' . $info['advertiser_id']); // 指定金额在该投放计划的今日回传人数

                        if (empty($thisLinkOrderNum) || empty($backSuccessNum)) {
                            // 这个链接所有支付成功的订单数（每个用户仅统计一次）
                            if (!empty($linkData['echo_rule_config_id'])) {
                                $thisLinkOrderNum = Db::name('pay_record')->where([
                                    'advertiser_id' => $info['advertiser_id'],
                                    'status' => 1,
                                    'activation_date' => date('Ymd'),
                                    'link_id' => $info['link_id'],
                                    'total_fee' => $info['total_fee']
                                ])->group('uid')->count();
                            } else {
                                $thisLinkOrderNum = Db::name('pay_record')->where([
                                    'advertiser_id' => $info['advertiser_id'],
                                    'status' => 1,
                                    'consume_date' => date('Ymd'),
                                    'link_id' => $info['link_id'],
                                    'total_fee' => $info['total_fee']
                                ])->group('uid')->count();
                            }

                            // 这个链接回传成功的数量（每个用户仅统计一次）
                            $where = [
                                ['link_id', '=', $info['link_id']],
                                ['advertiser_id', '=', $info['advertiser_id']],
                                ['status', '=', 1],
                                ['echo_amount', '=', $price],
                                ['echo_rule_config_id', '<>', '-1'],
                                ['created_at', 'between', [$startTime, $endTime]]
                            ];
                            $backSuccessNum = Db::name('transfer_back_record')->where($where)->group('uid')->count();

                            $redis->set('design-amount-pay-success-order-num-' . $price . '-' . date('Ymd') . '-' . $info['advertiser_id'], $thisLinkOrderNum, 3000);
                            $redis->set('design-amount-echo-success-order-num-' . $price . '-' . date('Ymd') . '-' . $info['advertiser_id'], $backSuccessNum, 3000);
                        } else {
                            // 有缓存回传数据
                            $redis->incr('design-amount-pay-success-order-num-' . $price . '-' . date('Ymd') . '-' . $info['advertiser_id']);
                            $thisLinkOrderNum = $thisLinkOrderNum + 1;
                        }

                        $type = 4;
                    }
                }
            } else {
                // 按常规回传率设置回传
                $echoNumData = $this->conventionalEcho($linkData, $redis, $info, $backData);
                $type = $echoNumData['type'];
                $thisLinkOrderNum = $echoNumData['this_link_order_num'];
                $backSuccessNum = $echoNumData['back_success_num'];
                // dump($echoNumData);die;
            }

            if (empty($thisLinkOrderNum)) {
                $thisLinkOrderNum = 1;
            }

            // 回传
            if ($type == 1 || $type == 2) {
                // 按常规比例回传
                if ($linkData['is_new_back_setting'] == 2 && empty($backData['back_rate_type'])) {
                    $echoRate = $backData['echo_rate'];
                } else {
                    $echoRate = $linkData['echo_rate'];
                }

                if (!empty($backData['back_rate_type'])) {
                    $sum = $backData['pass'] + $backData['leak'];
                    // 相加为0表示不回传
                    if (empty($sum)) {
                        $job->delete();
                        return;
                    }
                    if ($thisLinkOrderNum % $sum >= $backData['leak']) {
                        // 按循环比例回传
                        $boolId = $this->backPlatform($linkData, $info, 1);
                        if ($type == 1 && $boolId) {
                            $redis->incr('update-time-echo-success-order-num-' . $info['advertiser_id'] . '-' . $backData['edit_echo_time']); // redis成功回传数自增1
                        } else if ($type == 2 && $boolId) {
                            $redis->incr('echo-success-order-num-' . date('Ymd') . '-' . $info['advertiser_id']);
                        }
                    }
                } else {
                    if ($backSuccessNum / $thisLinkOrderNum < $echoRate / 100) {

                        // 小于回传比例
                        $boolId = $this->backPlatform($linkData, $info, 1);
                        if ($type == 1 && $boolId) {
                            if ($linkData['is_new_back_setting'] == 1) {
                                $editEchoRateTime = $linkData['edit_echo_rate_time'];
                            } else {
                                $editEchoRateTime = $backData['edit_echo_time'];
                            }
                            $redis->incr('update-time-echo-success-order-num-' . $info['advertiser_id'] . '-' . $editEchoRateTime); // redis成功回传数自增1
                        } else if ($type == 2 && $boolId) {
                            $redis->incr('echo-success-order-num-' . date('Ymd') . '-' . $info['advertiser_id']);
                        }
                    }
                }

            } else {

                // 按指定金额回传比例
                if ($backSuccessNum / $thisLinkOrderNum < $echoRate / 100) {
                    // 小于回传比例
                    $boolId = $this->backPlatform($linkData, $info, 1);
                    if ($type == 3 && $boolId) {
                        $redis->incr('design-amount-echo-success-order-num-' . $price . '-' . $updateTime . '-' . $info['advertiser_id']);
                    } else if ($type == 4 && $boolId) {
                        $redis->incr('design-amount-echo-success-order-num-' . $price . '-' . date('Ymd') . '-' . $info['advertiser_id']);
                    }
                }
            }

            // 如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
            $job->delete();

        } catch (\Exception $e) {
            // dump($e->getLine());
            // dump($e->getMessage());die;
            $job->delete();
            Log::error('****** ' . json_encode($info) . ' --//-- ' . '第 ' . $e->getLine() . ' 行' . '：' . $e->getMessage());
        }
    }

    // 按常规回传率设置回传
    public function conventionalEcho($linkData, $redis, $info, $backData = [])
    {
        $type = 2;
        $startTime = strtotime(date('Y-m-d' . ' 00:00:00'));
        $endTime = strtotime(date('Y-m-d' . ' 23:59:59'));

        if ($linkData['is_new_back_setting'] == 1) {
            $editEchoRateTime = $linkData['edit_echo_rate_time'];
        } else {
            $editEchoRateTime = $backData['edit_echo_time'];
        }

        if ($startTime < $editEchoRateTime && $endTime > $editEchoRateTime) { // 当天有修改回传率
            // 按该链接修改回传率的时间之后的支付数和回传数开始计算比例
            $backSuccessNum = $redis->get('update-time-echo-success-order-num-' . $info['advertiser_id'] . '-' . $editEchoRateTime); // 该投放计划的回传数
            $thisLinkOrderNum = $redis->get('update-time-pay-success-order-num-' . $info['advertiser_id'] . '-' . $editEchoRateTime); // 该投放计划的订单数

            if (empty($thisLinkOrderNum) || empty($backSuccessNum)) {
                $where = [
                    ['advertiser_id', '=', $info['advertiser_id']],
                    ['status', '=', 1],
                    ['pay_time', '>', $editEchoRateTime],
                    ['link_id', '=', $info['link_id']]
                ];
                // 这个链接修改回传率的时间之后的支付订单数（每个用户仅统计一次）
                $thisLinkOrderNum = Db::name('pay_record')->where($where)->group('uid')->count();
                // 这个链接修改回传率的时间之后的回传成功数（每个用户仅统计一次）
                $where = [
                    ['advertiser_id', '=', $info['advertiser_id']],
                    ['status', '=', 1],
                    ['created_at', '>', $editEchoRateTime],
                    ['link_id', '=', $info['link_id']],
                    ['echo_rule_config_id', '<>', '-1']
                ];
                $backSuccessNum = Db::name('transfer_back_record')->where($where)->group('uid')->count();

                $redis->set('update-time-echo-success-order-num-' . $info['advertiser_id'] . '-' . $editEchoRateTime, $backSuccessNum, 3000);
                $redis->set('update-time-pay-success-order-num-' . $info['advertiser_id'] . '-' . $editEchoRateTime, $thisLinkOrderNum, 3000); // redis存50分钟
            } else {
                // 有缓存回传数据
                $redis->incr('update-time-pay-success-order-num-' . $info['advertiser_id'] . '-' . $editEchoRateTime); // redis自增1
                $thisLinkOrderNum = $thisLinkOrderNum + 1;
            }
            $type = 1;
        } else {
            // 没有修改回传率时间则表示未修改过回传率
            $backSuccessNum = $redis->get('echo-success-order-num-' . date('Ymd') . '-' . $info['advertiser_id']); // 该投放计划的回传数
            $thisLinkOrderNum = $redis->get('pay-success-order-num-' . date('Ymd') . '-' . $info['advertiser_id']); // 该投放计划的订单数

            if (empty($thisLinkOrderNum) || empty($backSuccessNum)) {
                // 这个链接所有支付成功的订单数（每个用户仅统计一次）
                if ($linkData['echo_rule_config_id'] == 1) {
                    $thisLinkOrderNum = Db::name('pay_record')->where(['advertiser_id' => $info['advertiser_id'], 'status' => 1, 'activation_date' => date('Ymd'), 'link_id' => $info['link_id']])->group('uid')->count();
                } else {
                    $thisLinkOrderNum = Db::name('pay_record')->where(['advertiser_id' => $info['advertiser_id'], 'status' => 1, 'consume_date' => date('Ymd'), 'link_id' => $info['link_id']])->group('uid')->count();
                }

                // 这个链接回传成功的数量（每个用户仅统计一次）
                $where = [
                    ['link_id', '=', $info['link_id']],
                    ['advertiser_id', '=', $info['advertiser_id']],
                    ['status', '=', 1],
                    ['echo_rule_config_id', '<>', '-1'],
                    ['created_at', 'between', [$startTime, $endTime]]
                ];
                $backSuccessNum = Db::name('transfer_back_record')->where($where)->group('uid')->count();

                $redis->set('echo-success-order-num-' . date('Ymd') . '-' . $info['advertiser_id'], $backSuccessNum, 3000);
                $redis->set('pay-success-order-num-' . date('Ymd') . '-' . $info['advertiser_id'], $thisLinkOrderNum, 3000);
            } else {
                // 有缓存回传数据
                $redis->incr('pay-success-order-num-' . date('Ymd') . '-' . $info['advertiser_id']);
                $thisLinkOrderNum = $thisLinkOrderNum + 1;
            }
            $type = 2;
        }
        return ['type' => $type, 'this_link_order_num' => $thisLinkOrderNum, 'back_success_num' => $backSuccessNum];
    }

    // 付费按比例回传
    public function backPlatform($linkData, $info, $isFirst = 0)
    {
        $mediaId = $linkData['media_id'];
        $echoRuleId = $linkData['echo_rule_config_id'];

        if ($mediaId == 1) {
            // 抖音
            if (!empty($linkData['is_capitalization'])) {
                $token = config('tiktok.capitalization.token');
                $url = config('tiktok.capitalization.url');
                $timestamp = time();
                $rand = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
                shuffle($rand);

                $nonceArray = array_slice($rand, 0, 4);
                $nonce = implode('', $nonceArray);

                $collect = [(string)$token, (string)$nonce, (string)$timestamp];
                usort($collect, 'strcmp');
                $signature = sha1(implode('', $collect));

                $body = [
                    'clue_token' => $info['clickid'],
                    'open_id' => $info['open_id'],
                    'event_type' => '2',
                    'props' => [
                        'pay_amount' => intval($info['total_fee'] * 100)
                    ]
                ];

                $requestData = json_encode($body);
                $url = $url . '?timestamp=' . $timestamp . '&nonce=' . $nonce . '&signature=' . $signature;
                $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                $data = json_decode($result, true);
                $status = isset($data['status']) && $data['status'] == 200 ? 1 : 2; // 1成功 2失败
                $message = !empty($data['message']) ? $data['message'] : '成功'; // 回传巨量的响应提示
            } else {
                $url = 'https://analytics.oceanengine.com/api/v2/conversion';

                $requestData = [
                    'event_type' => 'active_pay',
                    'event_weight' => floatval($info['total_fee'] * 100),
                    'context' => [
                        'ad' => [
                            'callback' => $info['clickid']
                        ]
                    ],
                    'properties' => [
                        'pay_amount' => floatval($info['total_fee'] * 100),
                        'bill_track_type' => '1'
                    ],
                    'timestamp' => Common::msectime()
                ];

                $requestData = json_encode($requestData);
                $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
                $data = json_decode($result, true);
                $status = isset($data['code']) && $data['code'] == 0 ? 1 : 2; // 1成功 2失败
                $message = !empty($data['message']) ? $data['message'] : ''; // 回传巨量的响应提示
            }

        } else if ($mediaId == 2) {
            // 快手 https://yiqixie.qingque.cn/d/home/fcACjQFu3lSI1QT7ktc7TCH9e#
            $url = 'http://ad.partner.gifshow.com/track/activate';
            $requestData = [
                'callback' => $info['clickid'],
                'event_type' => 3,
                'event_time' => Common::msectime(),
                'purchase_amount' => $info['total_fee']
            ];

            $result = Common::_curl($url, $requestData, 'GET');
            $data = json_decode($result, true);
            $status = isset($data['result']) && $data['result'] == 1 ? 1 : 2;
            $message = !empty($data['error_msg']) ? '失败' : '成功';

        } else if ($mediaId == 3) {
            // 百度
            $url = 'https://ocpc.baidu.com/ocpcapi/api/uploadConvertData';
            $conversionTypes = [
                'logidUrl' => 'https://' . config('app.app_host') . '?bd_vid=' . $info['clickid'],
                'newType' => 118,
                'convertValue' => intval($info['total_fee'] * 100)
            ];

            $token = $linkData['token'];
            $datas = ['token' => $token, 'conversionTypes' => $conversionTypes];
            $requestData = json_encode($datas);
            $result = Common::curlRequest($url, 'POST', $requestData, ['Content-Type : application/json']);
            $data = json_decode($result, true);
            $status = $data['header']['status'] == 0 ? 1 : 2;
            $message = !empty($data['header']['errors']) ? $data['header']['errors']['message'] : '成功';
        } else if ($mediaId == 4) {
            // 腾讯下单回传
            try {
                $appletData = Db::name('applet')->where(['id' => $info['applet_id']])->field('app_id')->find();
                $videoData = Db::name('videos')->where(['id' => $linkData['video_id']])->field('name')->find();
                $url = urldecode($info['back_url']);

                $requestData = [
                    'actions' => [[
                        'action_time' => time(),
                        'user_id' => [
                            'wechat_openid' => $info['open_id'],
                            'wechat_app_id' => $appletData['app_id'],
                        ],
                        'trace'=>[
                            'click_id' => $info['clickid']
                        ],
                        'action_type' => 'PURCHASE',
                        'action_param' => [
                            'value' => intval($info['total_fee'] * 100),
                            'product_name' => $videoData['name'] . '-比翼鸟'
                        ]
                    ]]
                ];

                if ($isFirst) {
                    // 首充下单和付费都回传
                    $requestData1 = $requestData;
                    $requestData1['actions'][0]['action_type'] = 'COMPLETE_ORDER';
                    $result1 = Common::curlRequest($url, 'POST', json_encode($requestData1), ['Content-Type: application/json']); // 回传下单
                    $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']); // 回传付费
                } else {
                    // 复充只回传付费
                    $result = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']); // 回传付费
                }

                $data = json_decode($result, true);

                $status = $data['code'] == 0 ? 1 : 2;
                $message = $data['message'] != 'ok' ? $data['message'] : '成功';

            } catch (\Exception $e) {
                Log::error('****** '.json_encode($info).' --//-- '.'第 '.$e->getLine().' 行'.'：'.$e->getMessage());
                return true;
            }
        }
        // 组装回传记录数据
        $saveData = [
            'uid' => $info['uid'],
            'pay_id' => $info['id'],
            'media_id' => $mediaId,
            'link_id' => $info['link_id'],
            'created_at' => time(),
            'status' => $status,
            'message' => $message,
            'echo_rule_config_id' => $linkData['echo_rule_config_id'],
            'official_account_id' => $linkData['official_account_id'],
            'is_first_recharge' => $isFirst,
            'version' => 2,
            'advertiser_id' => $info['advertiser_id'],
            'echo_amount' => intval($info['total_fee'] * 100),
        ];

        // 添加回传记录
        Db::startTrans();
        try {
            $insertBool = Db::name('transfer_back_record')->insert($saveData);
            // 修改订单表数据是否回传 等于0表示成功
            if ($status == 1 && $insertBool) {
                $updateBool = Db::name('pay_record')->where(['id' => $info['id']])->update(['is_echo' => 1]);
            }

            if ($insertBool) {
                Db::commit();
            } else {
                Db::rollback();
            }
        } catch (\Exception $e) {
            // dump($e->getMessage());die;
            // 回滚事务
            Db::rollback();
            Log::error(json_encode($info).' -------- ' . $e->getLine() . '-' . $e->getMessage() . ' -------- ');
        }

        return true;
    }

    public function failed($data)
    {
        // ...任务达到最大重试次数后，失败了
        // Log::error('回传失败：'.json_encode($data));
    }
}